<template>
    <page-box>
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
                <ask-breadcrumb-item>{{$route.query.id ? "编辑" : "新增"}}</ask-breadcrumb-item>
            </ask-breadcrumb>
        </template>
        <div class="org-update-container">
            <div class="container-right">
                <p>{{$route.query.departmentName}}</p>
                <el-form class="add-member-form" ref="form" :rules="rules" :model="form" label-width="80px">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="form.name" placeholder="请输入成员姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="职位" prop="position">
                        <el-input v-model="form.position" placeholder="请输入成员职位"></el-input>
                    </el-form-item>
                    <el-form-item label="账号名" prop="phone">
                        <el-input v-model="form.phone" :readonly="readonly" autocomplete="off" placeholder="请输入成员联系电话,电话号码默认为用户的登录账号"></el-input>
                    </el-form-item>
                    <el-form-item label="登录密码" prop="password" v-if="!$route.query.id">
                        <el-input v-model="form.password" :readonly="readonly" type="text" autocomplete="off" placeholder="请设置6~12位数字字母组合新密码"></el-input>
                    </el-form-item>
                    <el-form-item label="关联角色" prop="roles">
                        <template v-if="rolesRenderList.length === 0">暂无角色</template>
                        <el-radio-group v-model="form.roles">
                            <el-radio v-for="(item, index) in rolesRenderList" :label="item.id" :key="index">{{item.name}}</el-radio>
                            <el-button v-if="rolesList.length > 8" type="text" @click="showMore = !showMore">{{showMore ? "收起" : "展开"}}</el-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="数据范围" v-if="_isOperation" prop="dataRange">
                        <ask-city-no-relation
                            cityQuery="authNoVillage"
                            ref="askCity"
                            multiple
                            clearable
                            :showIndex="4"
                            v-model="form.dataRange"
                            :showOperate="false"
                            @area-change="handleChange"></ask-city-no-relation>
                        <p class="tips">设置人员查看的额外{{ ["ADMIN","OPERATION_ADMIN","OPERATION"].includes(client) ? "区镇" : client.includes("REGIONAL") ? "镇" : "村" }}数据</p>

                    </el-form-item>
                    <el-form-item class="form-btn">
                        <el-button @click="goBack">取消</el-button>
                        <el-button type="primary" @click="onSubmit">提交</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </page-box>
</template>

<script lang="ts">
import Vue from "vue";
import { Component } from "vue-property-decorator";
import OrgTree from "@/components/org-tree/index.vue";
import { checkPassword } from "@/utils/vee-validate";
import { State } from "vuex-class";

const customCheckPassword = (rule: any, value: any, callback: any) => {
    if (!checkPassword(value)) {
        callback(new Error('请设置6~12位数字字母组合新密码'));
    } else {
        callback();
    }
};

const checkTel = (rule: any, value: any, callback: any) => {
    if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('请输入正确的联系电话'));
    } else {
        callback();
    }
};

@Component({
    name: "OrganizationUpdateNotAlive",
    components: {
        OrgTree
    }
})
export default class OrganizationUpdate extends Vue {
    @State(state => state.authArea) authArea: any;
    // 当前用户所处层级菜单
    get client() {
        return this.$getUserLevel(
            this.authArea && this.authArea.orgCategoryId
        ).name;
    }

    // 当前组织id
    orgId: any = "";

    form: any = {
        // id
        id: "",
        // 姓名
        name: "",
        // 职位
        position: "",
        // 联系电话
        phone: "",
        // 登录密码
        password: "",
        // 关联角色
        roles: "",
        // 数据范围
        dataRange: [],
        // 数据范围governmentId
        dataGovernments: []
    }

    // 角色列表
    rolesList = []
    // 数据范围列表
    dataRangeList = []
    // 显示更多
    showMore = false

    rules = {
        name: [
            { required: true, message: '请输入成员名称', trigger: 'change' },
            { max: 10, message: '最多输入10个字符', trigger: 'change' }
        ],
        position: [
            { max: 10, message: '最多输入10个字符', trigger: 'change' }
        ],
        phone: [
            { required: true, message: '请输入成员联系电话', trigger: 'change' },
            { validator: checkTel, trigger: 'change' }
        ],
        password: [
            { required: true, validator: customCheckPassword, trigger: 'change' }
        ],
        roles: [
            { required: true, message: '请选择一个角色关联' }
        ]
    }

    readonly = true

    get _isOperation() {
        return ['ADMIN', 'OPERATION_ADMIN', 'OPERATION'].includes(this.client);
    }

    get rolesRenderList() {
        return this.rolesList.splice(0, this.showMore ? this.rolesList.length : 8);
    }

    created() {
        this.getRoles();
        this.orgId = this.$route.query.orgId;
        if (this.$route.query.id) {
            this.form.id = this.$route.query.id;
            this.getMemberInfo();
        }
    }

    mounted() {
        setTimeout(() => {
            this.readonly = false;
        });
    }

    // 根据id获取用户信息
    async getMemberInfo() {
        const res = await this.$server["org/member/getInfo"]({
            data: {
                id: this.$route.query.id
            }
        });
        if (res.data.code === 200) {
            this.form.name = res.data.data.name;
            this.form.position = res.data.data.position;
            this.form.phone = res.data.data.tel;
            this.form.roles = res.data.data.roleIds.join(",");
            this.form.dataGovernments = res.data.data.governmentIds || [];
            const askCity: any = this.$refs.askCity;
            askCity && askCity.setIds(this.form.dataGovernments);
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 修改数据范围
    handleChange(values: any[], nodes: any[]) {
        this.form.dataGovernments = nodes.map((cur: any) => cur.data.id);
    }

    // 获取角色列表
    getRoles() {
        this.$server.getRole({
            data: {}
        }).then((res: any) => {
            if (res.data.code === 200) {
                this.rolesList = res.data.data.filter((item: any) => item.name);
            } else {
                this.$message.error(res.data.message || "接口请求错误!");
            }
        }).catch();
    }

    // 提交
    onSubmit() {
        (this.$refs.form as any).validate((valid: any) => {
            if (valid) {
                this.updatedMember();
            } else {
                console.log('error submit!!');
                return false;
            }
        });
    }

    // 新增/编辑用户
    updatedMember() {
        const { id, name, position, phone, password, roles } = this.form;
        this.$server["org/member/updated"]({
            data: {
                id,
                departmentId: this.orgId,
                name,
                roleIds: [roles],
                password,
                position,
                tel: phone,
                username: phone,
                governmentIds: this._isOperation ? this.form.dataGovernments : [this.authArea.governmentId]
            }
        }).then((res: any) => {
            if (res.data.code === 200) {
                this.$message.success(id ? "编辑成功" : "添加成功");
                this.$router.go(-1);
            } else {
                this.$message.error(res.data.message || "接口请求错误!");
            }
        }).catch();
    }

    // 懒加载
    lazyLoadChild(node: any, resolve: any) {
        const res: never[] = [];
        resolve(res);
    }

    goBack() {
        this.$router.go(-1);
    }
}
</script>

<style scoped lang="scss">
::v-deep {
    .page-base-body {
        height: calc(100% - 50px) !important;
    }
}
.org-update-container {
    display: flex;
    justify-content: center;
    align-items: flex-start;

    .container-right {
        margin-left: 0.2rem;
        .add-member-form {
            width: 6rem;
            .el-radio-group {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                flex-wrap: wrap;
                padding-top: 5px;
                .el-radio {
                    width: 25%;
                    margin: 5px 0;
                }
            }
            .tips {
                margin: 0;
                line-height: 1.5;
                color: #909497;
            }
            .form-btn {
                text-align: right;
            }
        }
    }
}
</style>
